package com.example.hongyu.avtt.ui.fragment;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.hongyu.avtt.R;
import com.example.hongyu.avtt.config.Constant;
import com.example.hongyu.avtt.event.Event;
import com.example.hongyu.avtt.listener.OnItemClickListener;
import com.example.hongyu.avtt.model.Vedio;
import com.example.hongyu.avtt.model.entity.BaseResponse;
import com.example.hongyu.avtt.model.response.WebSite;
import com.example.hongyu.avtt.network.BaseObserver;
import com.example.hongyu.avtt.network.RetrofitHelper;
import com.example.hongyu.avtt.network.RxUtil;
import com.example.hongyu.avtt.network.api.AppInfoApi;
import com.example.hongyu.avtt.ui.activity.PlayerActivity;
import com.example.hongyu.avtt.ui.adapter.TypeListAdapter;
import com.example.hongyu.avtt.ui.adapter.VedioListAdapter;
import com.example.hongyu.avtt.ui.adapter.WebSiteAdapter;
import com.example.hongyu.avtt.ui.base.BaseFragment;
import com.example.hongyu.avtt.util.AnimUtil;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.uni.taggroupview.TagGroupView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class VideoFragment extends BaseFragment {
    private final String TAG="VideoFragment";
    @BindView(R.id.xrecycle_view)
    XRecyclerView xRecyclerView;

    RecyclerView webRecyclerView;
    RecyclerView typeRecyclerView;
    @BindView(R.id.tag_view)
    TagGroupView tagView;
    VedioListAdapter vedioListAdapter;
    WebSiteAdapter webSiteListAdapter;
    TypeListAdapter typeListAdapter;
    List<Vedio> vedios=new ArrayList<>();
    List<WebSite> webSites=new ArrayList<>();
    List<Vedio> typeSites=new ArrayList<>();
    private int pageIndex=1;
    private int pageSize=100;
    String[] tag = new String[]{"网站","类型"};

    //判断是否已进行过加载，避免重复加载
    private boolean isLoad=false;
    //判断当前fragment是否可见
    private boolean isVisibleToUser = false;
    //判断当前fragment是否回调了resume
    private boolean isResume = false;
    int dataSize=0;
    private String webSite="";
    private String tyName="";
    private PopupWindow popupWindow;
    private AnimUtil animUtil;
    private float bgAlpha = 1f;
    private boolean bright = false;
    @Override
    protected View getContentView(LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(R.layout.fragment_vedio, container, false);
    }

    @Override
    protected void initView() {
        webSiteListAdapter=new WebSiteAdapter(this.getContext(),webSites);
        typeListAdapter=new TypeListAdapter(this.getContext(),typeSites);
        View popView=View.inflate(this.getContext(),R.layout.recycleview_pop,null);
        webRecyclerView=popView.findViewById(R.id.recycle_view1);
        webRecyclerView.setLayoutManager(new GridLayoutManager(this.getContext(),2));
        webRecyclerView.setAdapter(webSiteListAdapter);
        typeRecyclerView=popView.findViewById(R.id.recycle_view2);
        typeRecyclerView.setLayoutManager(new GridLayoutManager(this.getContext(),2));
        typeRecyclerView.setAdapter(typeListAdapter);
        popupWindow=new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                toggleBright();
            }
        });


        webSiteListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                webSite=webSites.get(position).getName();
                if (popupWindow.isShowing()){
                    popupWindow.dismiss();
                }
                httpGetVideoList(1,true);
            }
        });
        typeListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                tyName=typeSites.get(position).getTitle();
                tag[1]=tyName;
                if (popupWindow.isShowing()){

                    popupWindow.dismiss();
                }
                httpGetVideoList(1,true);
            }
        });


        xRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        vedioListAdapter=new VedioListAdapter(this.getContext(),vedios);
        xRecyclerView.setAdapter(vedioListAdapter);

        xRecyclerView.setPullRefreshEnabled(true);
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                pageIndex=1;
                httpGetVideoList(pageIndex, true);
            }

            @Override
            public void onLoadMore() {
                pageIndex++;
                httpGetVideoList(pageIndex, false);
            }
        });
        vedioListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Vedio vedio=vedios.get(position-1);
                httpUpDateVideoPlayTimes(vedio);

//

            }
        });
        tagView.setData(tag);
        // 监听点击
        tagView.setOnTabChangeListener((v, index, isOpen) -> {
                Log.i("tagView.isOpen",""+isOpen);
                if (index==0) {

                    if (!isOpen) {
                        webRecyclerView.setVisibility(View.GONE);
                        typeRecyclerView.setVisibility(View.GONE);
                    } else {
                        webRecyclerView.setVisibility(View.VISIBLE);
                        typeRecyclerView.setVisibility(View.GONE);
                    }
                }
            if (index==1) {

                if (!isOpen) {
                    webRecyclerView.setVisibility(View.GONE);
                    typeRecyclerView.setVisibility(View.GONE);
                } else {
                    webRecyclerView.setVisibility(View.GONE);
                    typeRecyclerView.setVisibility(View.VISIBLE);
                }
            }

                if (!isOpen){
                    popupWindow.dismiss();

                }else {
                    toggleBright();
                    popupWindow.showAsDropDown(tagView, 0,10,Gravity.BOTTOM);
                }





        });
        httpGetVideoWebSiteList();

    }

    private void toggleBright() {
        //三个参数分别为： 起始值 结束值 时长 那么整个动画回调过来的值就是从0.5f--1f的
        animUtil.setValueAnimator(0.5f, 1f, 350);
        animUtil.addUpdateListener(new AnimUtil.UpdateListener() {
            @Override
            public void progress(float progress) {
                //此处系统会根据上述三个值，计算每次回调的值是多少，我们根据这个值来改变透明度
                bgAlpha = bright ? progress : (1.5f - progress);//三目运算，应该挺好懂的。
                backgroundAlpha(bgAlpha);//在此处改变背景，这样就不用通过Handler去刷新了。
            }
        });
        animUtil.addEndListner(new AnimUtil.EndListener() {
            @Override
            public void endUpdate(Animator animator) {
                //在一次动画结束的时候，翻转状态
                bright = !bright;
            }
        });
        animUtil.startAnimator();
    }

    /***
     * 此方法用于改变背景的透明度，从而达到“变暗”的效果
     */
    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        this.getActivity().getWindow().setAttributes(lp);
        this.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }



    @SuppressLint("AutoDispose")
    private void httpUpDateVideoPlayTimes(Vedio vedio) {
        RetrofitHelper.create(AppInfoApi.class)
                .upDatePalytimes(vedio.getWebSite(),vedio.getId())
                .compose(RxUtil.observervableToMain())
                .subscribe( new BaseObserver<Object>(getLoadingDialog()) {
                    @Override
                    public void onSuccess(BaseResponse<Object> response) {
                        String url=vedio.getPath();
                        String name=vedio.getTitle();
                        Intent intent =  new Intent();
                        intent.setAction( "android.intent.action.VIEW" );
                        Uri content_url = Uri.parse(url);
                        intent.setData(content_url);
                        startActivity(intent);
    //                  mBundle=getBundle();
    //                if (mBundle==null){
    //                    mBundle=new Bundle();
    //                }
    //                mBundle.putString("PLAYURL",url);
    //                mBundle.putString("PLAYNAME",name);
    //                sendIntent(PlayerActivity.class,mBundle);

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    @Override
    protected void initData() {
        animUtil = new AnimUtil();

    }
    @SuppressLint("AutoDispose")
    private void httpGetVideoWebSiteList() {
        RetrofitHelper.create(AppInfoApi.class)
                .vedioWebSiteList()
                .compose(RxUtil.observervableToMain())
                .subscribe( new BaseObserver<List<WebSite>>(getLoadingDialog()) {
                    @Override
                    public void onSuccess(BaseResponse<List<WebSite>> response) {
                        if (response != null && response.getData() != null) {
                            webSites.clear();
                            webSites.addAll(response.getData());
                            webSiteListAdapter.notifyDataSetChanged();
                            if(webSites.size()>0){
                                webSite=webSites.get(0).getName();
                                tag[0]=webSite;

                            }else {
                                webSite="";
                            }





                        }
                        httpgetVideoTypeList();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    @Override
    protected void onEventProcess(Event event) {
        int code=event.getCode();
        switch (code){
            
            case Constant.REFRESH_PAGE_DATA_EVENT:
                httpGetVideoWebSiteList();
                pageIndex=1;
                httpGetVideoList(pageIndex, true);
                break;
            case Constant.DISMISS_RECYCLEVIEW_EVENT:
                    Toast.makeText(this.getContext(), "****", Toast.LENGTH_SHORT).show();
                    popupWindow.dismiss();

                break;
            case Constant.SHOW_RECYCLEVIEW_EVENT:
                    Toast.makeText(this.getContext(), "index=" + "****", Toast.LENGTH_SHORT).show();


                    break;
        }

    }
    @SuppressLint("AutoDispose")
    private void httpGetVideoList(int index, boolean isRefresh) {

        RetrofitHelper.create(AppInfoApi.class)
                .vedioList("",webSite,tyName,pageIndex,pageSize)
                .compose(RxUtil.observervableToMain())
                .subscribe( new BaseObserver<List<Vedio>>(getLoadingDialog()){
                    @Override
                    public void onSuccess(BaseResponse<List<Vedio>> response) {
                        if (response!=null&&response.getData()!=null){
                            if(isRefresh){
                                vedios.clear();
                                xRecyclerView.refreshComplete();
                            }else {
                                dataSize=response.getData().size();
                                xRecyclerView.loadMoreComplete();


                            }

                            vedios.addAll(response.getData());

                            vedioListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if(isRefresh){
                            xRecyclerView.refreshComplete();
                        }else {
                            pageIndex--;
                            xRecyclerView.loadMoreComplete();
                        }
                    }
                });
    }
    @Override
    public void onResume() {
        super.onResume();
        isResume=true;
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.i(TAG, "setUserVisibleHint: "+isVisibleToUser+""+this);
        this.isVisibleToUser=isVisibleToUser;
        lazyLoad();
    }

    private void lazyLoad() {
        if (!isLoad&&isVisibleToUser&&isResume){




            isLoad=true;
        }
    }

    @SuppressLint("AutoDispose")
    private void httpgetVideoTypeList() {
        RetrofitHelper.create(AppInfoApi.class)
                .vedioTypeSiteList(webSite)
                .compose(RxUtil.observervableToMain())
                .subscribe( new BaseObserver<List<Vedio>>(getLoadingDialog()) {
                    @Override
                    public void onSuccess(BaseResponse<List<Vedio>> response) {
                        if (response != null && response.getData() != null) {
                            typeSites.clear();
                            typeSites.addAll(response.getData());
                            typeListAdapter.notifyDataSetChanged();
                            if (typeSites.size()>0) {
                                tyName = typeSites.get(0).getTitle();
                            }else {
                                tyName="";
                            }
                            tag[1]=tyName;
                            httpGetVideoList(pageIndex,true);

                        }
                    }
                });
    }

    @Override
    public void onPause() {
        super.onPause();
        if(popupWindow!=null&&popupWindow.isShowing()){
            popupWindow.dismiss();
        }
    }
}

